/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-01-06
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-02-07
 * @Description: 
 */
import 'package:flutter/material.dart';

class PopupMenu extends StatefulWidget {
  final VoidCallback onClose;
  final Offset offset;
  final LayerLink layerLink;
  final List<MenuItem> menuItems; // 动作项列表

  const PopupMenu({
    required this.onClose,
    required this.offset,
    required this.layerLink,
    required this.menuItems, // 接受动态传入的菜单项
    Key? key,
  }) : super(key: key);

  @override
  State<PopupMenu> createState() => _PopupMenuState();
}

class _PopupMenuState extends State<PopupMenu>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  static const double _triangleSize = 20.0;
  static const double _triangleHeight = 16.0;
  static const double _popupPadding = 16.0;
  static const double _popupVerticalPadding = 12.0;
  static const double _iconSize = 30.0;
  static const double _iconInnerSize = 18.0;
  static const double _iconSpacing = 8.0;
  static const double _itemSpacing = 12.0;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 300),
    );
    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  // 关闭弹窗
  void _handleClose() {
    _controller.reverse().then((_) => widget.onClose());
  }

  // 点击外部关闭弹窗
  void _onTapOutside() {
    _handleClose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _onTapOutside, // 点击外部区域关闭弹窗
      behavior: HitTestBehavior.translucent,
      child: ScaleTransition(
        scale: CurvedAnimation(
          parent: _controller,
          curve: _controller.isCompleted ? Curves.easeOut : Curves.easeIn,
        ),
        alignment: Alignment.topRight,
        child: Stack(
          children: [
            Positioned(
              left: widget.offset.dx - 100, // 微调偏移
              top: widget.offset.dy + 60, // 微调偏移
              child: CompositedTransformFollower(
                link: widget.layerLink,
                showWhenUnlinked: false,
                offset: const Offset(-90, 50),
                child: Material(
                  color: Colors.transparent,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      CustomPaint(
                        size: const Size(_triangleSize, _triangleHeight),
                        painter: _TrianglePainter(),
                      ),
                      _buildPopupContent(),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 构建弹窗内容，支持动态的菜单项
  Widget _buildPopupContent() {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xFF4C4C4C).withOpacity(0.95),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Padding(
        padding: const EdgeInsets.symmetric(
            horizontal: _popupPadding, vertical: _popupVerticalPadding),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: widget.menuItems
              .map((item) => Column(
                    children: [
                      _buildActionItem(item.icon, item.text, item.onTap),
                      const SizedBox(height: _itemSpacing),
                    ],
                  ))
              .toList(),
        ),
      ),
    );
  }

// 创建每个动作项，图标和文字水平排列
  Widget _buildActionItem(IconData icon, String text, VoidCallback onTap) {
    return GestureDetector(
      onTap: () {
        onTap();
        _handleClose(); // 点击时关闭弹窗
      },
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start, // 左对齐
        children: [
          Container(
            width: _iconSize, // 缩小图标尺寸
            height: _iconSize,
            decoration: BoxDecoration(
              color: Colors.grey[800]!.withOpacity(0.6),
              shape: BoxShape.circle,
            ),
            child:
                Icon(icon, color: Colors.white, size: _iconInnerSize), // 缩小图标
          ),
          const SizedBox(width: _iconSpacing), // 图标和文字之间的间距
          Text(
            text,
            style: const TextStyle(
                color: Colors.white,
                fontSize: 14,
                fontWeight: FontWeight.w500), // 增大文字
          ),
        ],
      ),
    );
  }
}

// 菜单项类，便于动态传入
class MenuItem {
  final IconData icon;
  final String text;
  final VoidCallback onTap;

  MenuItem({
    required this.icon,
    required this.text,
    required this.onTap,
  });
}

// 绘制指示器的三角形
class _TrianglePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = const Color(0xFF4C4C4C).withOpacity(0.95)
      ..style = PaintingStyle.fill;

    canvas.translate(size.width * 2, 0);

    final path = Path();
    path.moveTo(size.width / 2, 0);
    path.lineTo(size.width, size.height);
    path.lineTo(0, size.height);
    path.close();

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
